<template>
	<div class="category">
		<!-- 1.0 头部导航结构 -->
		<MyNavbar title="频道管理"></MyNavbar>

		<div class="main">
			<!-- 关注的标签 -->
			<h3 class="title">已关注频道</h3>
			<p class="desc">点击删除频道</p>
			<div class="tags">
				<van-tag
					class="items"
					v-for="item in followList"
					:key="item.id"
					type="success"
					size="large"
					closeable
					@close="followFn(item.id, true)"
				>
					{{ item.name }}
				</van-tag>
			</div>
			<!-- 全部标签 -->
			<h3 class="title">全部频道</h3>
			<p class="desc">点击添加频道</p>
			<div class="tags all">
				<van-tag
					:plain="!item.isFollow"
					class="items"
					v-for="item in categoryList"
					:key="item.id"
					type="primary"
					size="large"
					@click="followFn(item.id)"
				>
					{{ item.name }}
				</van-tag>
			</div>
		</div>
	</div>
</template>

<script>
import { getCategoryAPI } from '@/api/category.js';
import MyNavbar from '../components/MyNavbar.vue';
import { removeCategory, getCategory, setCategory } from '../utils/localStorage.js';
export default {
	components: {
		MyNavbar
	},
	async created() {
		// 本地存储中有则不请求
		if (this.categoryList.length) return;
		// 发起请求
		const { data } = (await getCategoryAPI()).data;
		// console.log(data);
		this.categoryList = data.map(item => ({ ...item, isFollow: true }));
	},
	data() {
		return {
			categoryList: getCategory()
		};
	},
	computed: {
		// 关注列表
		followList() {
			return this.categoryList
				? this.categoryList.filter(item => item.isFollow === true)
				: [];
		}
	},
	watch: {
		// 保存在本地
		categoryList: {
			deep: true,
			handler() {
				setCategory(this.categoryList)
			}
		}
	},
	methods: {
		// 双向
		followFn(id, del) {
			// console.log(id)
			// 根据id找下标
			const index = this.categoryList.findIndex(item => item.id === id);
			// 根据下标找值
			const { isFollow } = this.categoryList[index];
			// 至少保留两个频道
			if (this.followList.length <= 2 && isFollow)
				return this.$toast.fail('请至少保留两个频道！');
			// 直接删除
			if (del) return (this.categoryList[index].isFollow = false);
			// 取反
			this.categoryList[index].isFollow = !isFollow;
		}
	}
};
</script>

<style lang="less" scoped>
.main {
	padding: 10px;
	line-height: 2;
	.title {
		font-size: 18px;
	}
	.desc {
		color: #ccc;
		font-size: 13px;
	}
	.tags {
		margin: 10px 0;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-evenly;
		.items {
			margin: 5px;
		}
	}
	.all {
		// width: 200px;
		padding: 0 40px;
		.items {
			// margin: 5px 20px;
		}
	}
}
</style>
